﻿using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using GreetingCreatorGraphicUserControls.BackgroundAnimationCustomControl;

namespace GreetingCreatorGraphicUserControls
{
    public partial class BackgroundAnimationControl : UserControl
    {
        private int _maxAnimatedItems;
        private bool itemCreated;

        [SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")]
        public BackgroundAnimationControl()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(OnLoaded);
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            LayoutRoot.SizeChanged += LayoutRoot_SizeChanged;
            this.StartAnimation(30);
        }

        public void StartAnimation(int maxAnimatedItems)
        {
            _maxAnimatedItems = maxAnimatedItems;

            SetClipToLayoutRootGrid();

            if (itemCreated == false)
                CreateAllItemsAddItToGridAndStartAnimation(_maxAnimatedItems);
        }

        private void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            SetClipToLayoutRootGrid();
        }

        private void SetClipToLayoutRootGrid()
        {
            LayoutRoot.Clip = BuildRectangleGeometry();
        }

        private Geometry BuildRectangleGeometry()
        {
            var rectagleGeometry = new RectangleGeometry
                                       {
                                           Rect = new Rect(0, 0, LayoutRoot.ActualWidth, LayoutRoot.ActualHeight)
                                       };

            return (rectagleGeometry);
        }

        private void CreateAllItemsAddItToGridAndStartAnimation(int maxAnimatedItems)
        {
            for (int i = 0; i < maxAnimatedItems; i++)
            {
                UserControl item = CreateItem();
                AddItemToGrid(item);
                StartAnimationForItem(item);
            }

            itemCreated = true;
        }

        private UserControl CreateItem()
        {
            return (new ItemFactory().CreateItem(LayoutRoot));
        }

        private void StartAnimationForItem(UserControl item)
        {
            var storyboardFactory = new StoryboardFactory();
            Storyboard storyboard = storyboardFactory.CreateStoryboardAddItToGrid(item, LayoutRoot);

            BeginAnimationAndLoopForEver(storyboard);
        }

        private void BeginAnimationAndLoopForEver(Storyboard storyboard)
        {
            storyboard.Begin();
            storyboard.RepeatBehavior = RepeatBehavior.Forever;
        }

        private void AddItemToGrid(UIElement item)
        {
            LayoutRoot.Children.Add(item);
        }
    }
}